import Vue from 'vue'
import axios from 'axios'
import consts from './consts'
import * as wx from './wxShare'

// 配置axios

if (process.env.NODE_ENV === 'development') {} else {
  axios.defaults.baseURL = 'http://' + consts.domain
}
axios.defaults.withCredentials = true

axios.defaults.transformRequest = [
  function (data) {
    let ret = ''
    for (let it in data) {
      if (Array.isArray(data[it])) {
        data[it].forEach(item => {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(item) + '&'
        })
      } else {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
    }
    return ret
  }
]
axios.defaults.params = {}

// 拦截response 事先统一处理
axios.interceptors.response.use(
  function (response) {
    if (response.data.share_img) {
      // 微信分享
      wx.getSignature(response.data.share_img, response.data.share_title, response.data.share_introduce)
    }
    return response
  },
  function (error) {
    // Do something with response error
    return Promise.reject({
      msg: '网络错误',
      err: error
    })
  }
)
// 把axios放到全局中
Vue.prototype.$http = axios